package cn.edu.bupt.freewings.forum.persistence;

import cn.edu.bupt.freewings.forum.persistence.EntityManagerHelper;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import javax.persistence.EntityManager;
import javax.persistence.Query;

public class UserDAO {
	public void save(User entity) {
		try {
			EntityManagerHelper.getEntityManager().persist(entity);
		} catch (RuntimeException re) {
			re.printStackTrace();
		}
	}

	public void delete(User entity) {
		try {
			User ref = EntityManagerHelper.getEntityManager().getReference(
					User.class, entity.getId());
			EntityManagerHelper.getEntityManager().remove(ref);
		} catch (RuntimeException re) {
			re.printStackTrace();
		}
	}

	public User findById(Integer id) {
		try {
			User instance = EntityManagerHelper.getEntityManager().find(User.class,
					id);
			return instance;
		} catch (Exception e) {
			return null;
		}
	}

	public User update(User entity) {
		try {
			User result = EntityManagerHelper.getEntityManager().merge(entity);
			return result;
		} catch (Exception e) {
			return null;
		}
	}
	
	public User findByName(String name){
		try{
			String queryString = "select model from User model where model.name = :name";
			Query query = EntityManagerHelper.getEntityManager().createQuery(queryString);
			query.setParameter("name", name);
			return (User)query.getSingleResult();
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
}